<template>
  <div class="mood-detail">
    <!-- 顶部导航栏 -->
    <t-navbar title="动态详情" left-arrow @left-click="backPage" class="navbar">
      <template #right>
        <t-icon name="ellipsis" size="24px" />
      </template>
    </t-navbar>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="user-info">
          <t-image shape="circle" class="avatar" :src="moodData.imageurl"/>
          <div class="user-meta">
            <div class="nickname">{{mood.nickname}}</div>
            <div class="post-time">
              {{mood.createTime}}<br/>
              来自{{mood.address}}
            </div>
          </div>
        </div>
        <div class="like-action">
          <icon-font @click="addLike" :name="likeName" class="like-icon"/>
        </div>
      </div>

      <!-- 动态内容 -->
      <div class="mood-text">
        {{mood.content}}
      </div>

      <!-- 图片网格 -->
      <div v-if="hasImages" class="image-grid">
        <div v-if="mood.img1" class="image-item">
          <t-image :src="mood.img1" class="grid-image"/>
        </div>
        <div v-if="mood.img2" class="image-item">
          <t-image :src="mood.img2" class="grid-image"/>
        </div>
        <div v-if="mood.img3" class="image-item">
          <t-image :src="mood.img3" class="grid-image"/>
        </div>
        <div v-if="mood.img4" class="image-item">
          <t-image :src="mood.img4" class="grid-image"/>
        </div>
        <div v-if="mood.img5" class="image-item">
          <t-image :src="mood.img5" class="grid-image"/>
        </div>
        <div v-if="mood.img6" class="image-item">
          <t-image :src="mood.img6" class="grid-image"/>
        </div>
      </div>

      <!-- 动态数据统计 -->
      <div class="mood-stats">
        <span>阅读量：{{moodData.readNum || 0}}</span>
        <span class="stats-divider"></span>
        <span>点赞量：{{mood.likes || 0}}</span>
      </div>

      <!-- 评论区域 -->
      <div class="comment-section">
        <div class="section-header">
          <span class="section-title">评论 <span class="comment-count">{{moodData.comments || 0}}</span></span>
          <span class="section-extras">{{moodData.clikes || 0}} 赞</span>
        </div>
        
        <!-- 评论列表 -->
        <div>
          <comment-item 
            :comments="comments" 
            :class="commentTextClass"
            @add-comment-like="addCommentLike"
          ></comment-item>
        </div>
      </div>
    </div>

    <!-- 底部评论栏 -->
    <div class="comment-bar">
      <t-input 
        v-model="comment.content" 
        placeholder="我来说两句" 
        class="comment-input"
      ></t-input>
      <t-button 
        class="send-btn" 
        theme="primary" 
        size="small" 
        @click="addComment"
      >发表</t-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {DivideIcon, Icon as TIcon} from 'tdesign-icons-vue-next';
import {computed, onMounted, ref} from "vue";
import CommentItem from "../components/CommentItem.vue";
import { IconFont } from 'tdesign-icons-vue-next';
import {get, post} from "../util/Request";
import {Toast} from "tdesign-mobile-vue";

const mood=ref({})
const moodData=ref({})
const comment=ref({
  uid:sessionStorage.getItem("uid"),
  address:"",
  content:""
})
const likeName=ref("heart")
const comments=ref([])
const isLiked = ref(false); // 控制红心图标的显示状态
const currentPage = ref(1); // 当前页码
const pageSize = 10; // 每页显示数量

// 为评论添加文本颜色类
const commentTextClass = ref('dark-text')

// 计算属性，检查是否有图片
const hasImages = computed(() => {
  return mood.value.img1 || mood.value.img2 || mood.value.img3 || 
         mood.value.img4 || mood.value.img5 || mood.value.img6;
})

const backPage=()=>{
  history.back()
}

onMounted(()=>{
  mood.value=JSON.parse(localStorage.getItem("mood"))
  loadComment()
  get("mood/detail?id="+mood.value.id).then(res=>{
    moodData.value=res.data.data
    checkIfLiked() // 检查是否被喜欢
  })
})

const checkIfLiked = async () => {
  const uid = sessionStorage.getItem("uid");
  const mid = mood.value.id; // 当前动态的 mid
  try {
    const res = await get(`mlike/check?uid=${uid}&mid=${mid}`);
    isLiked.value = res.data.code === 200 && res.data.data === 1; // 根据返回结果设置红心状态
    if(isLiked.value){
      likeName.value="heart-filled";
    }else{
      likeName.value="heart";
    }
  } catch (error) {
    console.error("检查喜欢状态失败:", error);
  }
};

const addLike=()=>{
  post("mlike/add",{
    uid:sessionStorage.getItem("uid"),
    lid:mood.value.id
  }).then(res=>{
    if(likeName.value=="heart"){
      likeName.value="heart-filled";
      mood.value.likes = (mood.value.likes || 0) + 1;
    }else{
      likeName.value="heart";
      mood.value.likes = (mood.value.likes || 0) - 1;
    }
  })
}

const loadComment = () => {
  const uid = sessionStorage.getItem("uid");
  get(`comment/page?page=${currentPage.value}&size=${pageSize}&mid=${mood.value.id}&uid=${uid}`)
    .then(res => {
      if (res.data.data.data.length > 0) {
        comments.value.push(...res.data.data.data);
        console.log("评论数据：", comments.value);
      }
    })
    .catch(error => {
      console.error("加载评论失败:", error);
    });
}

const addComment = () => {
  if (!comment.value.content.trim()) {
    Toast("评论内容不能为空");
    return;
  }
  comment.value.mid = mood.value.id
  comment.value.uid = sessionStorage.getItem("uid")

  //请求 接口 实现评论 发布
  post("comment/add",comment.value).then(res=>{
    if(res.data.code==200){
      Toast("评论发布成功！")
      comment.value.content = "";
      moodData.value.comments = (moodData.value.comments || 0) + 1;
      //加载评论
      loadComment()
    }
  })
}

const addCommentLike = async (cid: number) => {
  const uid = sessionStorage.getItem("uid");
  if (!uid) {
    Toast("请先登录");
    return;
  }
  try {
    const res = await post("http://localhost:8181/api/clike/add", {
      uid,
      cid
    });
    if (res.data.code === 200) {
      Toast("点赞成功");
      // 从响应数据中获取最新的点赞数
      const newLikes = res.data.data?.likes; 
      if (typeof newLikes === 'number') {
        const comment = comments.value.find((c: any) => c.id === cid);
        if (comment) {
          comment.likes = newLikes;
        }
      }
    } else {
      Toast("点赞失败");
    }
  } catch (error) {
    console.error("点赞请求出错:", error);
    Toast("点赞请求出错，请稍后重试");
  }
};
</script>

<style scoped>
.mood-detail {
  min-height: 100vh;
  background-color: #f6f6f6;
  position: relative;
  padding-bottom: 60px;
  margin: 0;
  padding-top: 0;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background-color: #ffffff;
  border: none;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

:deep(.t-navbar) {
  background-color: #ffffff !important;
  border-bottom: none !important;
}

:deep(.t-navbar::before) {
  display: none !important;
}

:deep(.t-navbar::after) {
  display: none !important;
}

.content {
  margin-top: -2px;
  padding-bottom: 20px;
  background-color: #f6f6f6;
}

/* 用户信息卡片 */
.user-card {
  background-color: #ffffff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  border: 1px solid #eee;
}

.user-meta {
  display: flex;
  flex-direction: column;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 4px;
}

.post-time {
  font-size: 12px;
  color: #999999;
}

.like-action {
  padding: 8px;
}

.like-icon {
  font-size: 20px;
  color: #ff4d4f;
}

/* 动态内容区域 */
.mood-text {
  padding: 16px;
  font-size: 16px;
  line-height: 1.6;
  color: #333333;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  word-break: break-word;
}

/* 图片网格 */
.image-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 12px;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.image-item {
  width: 33.333%;
  padding: 4px;
  box-sizing: border-box;
}

.grid-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

/* 统计信息 */
.mood-stats {
  padding: 12px 16px;
  font-size: 13px;
  color: #666666;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.stats-divider {
  width: 1px;
  height: 12px;
  background-color: #dddddd;
  margin: 0 12px;
}

/* 评论区域 */
.comment-section {
  background-color: #ffffff;
  margin-top: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.comment-count {
  font-weight: normal;
  color: #666666;
  margin-left: 4px;
}

.section-extras {
  font-size: 14px;
  color: #999999;
}

.comment-list {
  padding: 16px;
}

/* 底部评论栏 */
.comment-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 16px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
  z-index: 9;
}

.comment-input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 20px;
}

.send-btn {
  margin-left: 12px;
  border-radius: 4px;
}

/* 评论文字颜色覆盖 */
.dark-text {
  color: #333333; /* 去掉 !important */
}

/* 只对特定的评论内容元素设置颜色，而不是所有后代元素 */
.dark-text :deep(.comment-content),
.dark-text :deep(.comment-nickname),
.dark-text :deep(.comment-info),
.dark-text :deep(.comment-time) {
  color: #333333; /* 去掉 !important */
}

/* 确保评论区内所有文字元素都有颜色 */


:deep(.comment-item) {
  color: #333333;
}

:deep(.comment-content) {
  color: #333333;
}

:deep(.comment-nickname) {
  color: #333333;
  font-weight: 500;
}

:deep(.comment-info) {
  color: #666666;
}

:deep(.comment-time) {
  color: #999999;
}
</style>
